package com.android.fragmentdemo.defineviews
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class DefineHandleFocusRecyclerView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : RecyclerView(context, attributeSet) {

    override fun onRequestFocusInDescendants(
        direction: Int,
        previouslyFocusedRect: Rect?
    ): Boolean {
        if (layoutManager is GridLayoutManager?) {
            val lm = layoutManager as? GridLayoutManager
            var nextPos = -1
            when (direction) {
                View.FOCUS_UP -> {
                    nextPos = 0
                }

                View.FOCUS_DOWN -> {
                    nextPos = (adapter?.itemCount ?: 0) - 1
                }

                View.FOCUS_LEFT, View.FOCUS_RIGHT -> {
                    val focusedView = findFocus()
                    if (focusedView != null) {
                        nextPos = lm?.getPosition(focusedView) ?: -1
                    }
                }
            }

            if (adapter != null
                && nextPos >= 0
                && nextPos < adapter!!.itemCount - 1) {
                lm?.findViewByPosition(nextPos)?.requestFocus(direction, previouslyFocusedRect)
            }
        }

        return super.onRequestFocusInDescendants(direction, previouslyFocusedRect)
    }
}